package com.wu.controller;

import com.wu.enums.SystemEnum;
import com.wu.enums.UserSessionEnum;
import com.wu.exception.BusinessException;
import com.wu.pojo.dto.SessionUserDto;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Objects;

public class BaseController {

    public HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public HttpSession getSession() {
        return getRequest().getSession();
    }

    public String getSessionUserName(HttpServletRequest request) {
        SessionUserDto sessionUser = getSessionUser(request);
        return sessionUser.getUsername();
    }

    public String getSessionUserRealName(HttpServletRequest request) {
        HttpSession session = request.getSession();
        return (String) session.getAttribute(UserSessionEnum.SESSION_USER_REAL_NAME_KEY.getKey());
    }

    public Long getSessionUserId(HttpServletRequest request) {
        HttpSession session = request.getSession();
        Object attribute = session.getAttribute(UserSessionEnum.SESSION_USER_ID_KEY.getKey());
        if (Objects.isNull(attribute)) {
            throw new BusinessException(SystemEnum.INVALID);
        }
        return Long.parseLong(attribute.toString());
    }

    public Long getSessionUserId() {
        return this.getSessionUserId(this.getRequest());
    }

    public SessionUserDto getSessionUser(HttpServletRequest request) {
        HttpSession session = request.getSession();
        return (SessionUserDto) session.getAttribute(UserSessionEnum.SESSION_USER_KEY.getKey());
    }

    public SessionUserDto getSessionUser() {
        return this.getSessionUser(this.getRequest());
    }

    public HttpSession getSession(HttpServletRequest request) {
        return request.getSession();
    }

    public String getSessionUrl(HttpServletRequest request) {
        StringBuffer sb = new StringBuffer();
        sb.append(request.getScheme());
        sb.append("://");
        sb.append(request.getServerName());
        sb.append(":");
        sb.append(request.getServerPort());
        sb.append(request.getContextPath());
        return sb.toString();
    }

    public Long getDepartmentId() {
        return getSessionUser().getDepartmentId();
    }


}

